package activitys;

import io.web.JSONConnector;
import java.util.ArrayList;
import java.util.List;
import misc.BasewarsConfig;
import misc.Sha1;
import nl.preflag.basewars.R;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener {
	
	private EditText etUsername;
	private EditText etPassword;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		// get all elements in the layout
    	Button btnSubmit = (Button) findViewById(R.id.loginSubmit);
    	btnSubmit.setOnClickListener(this);
    	
    	this.etUsername = (EditText) findViewById(R.id.loginUsername);
    	this.etPassword = (EditText) findViewById(R.id.loginPassword);
	}
	

    /**
     * Handles the click events from the buttons
     * @param v the View that is clicked
     */
	public void onClick(View v) {
		switch(v.getId())
		{
			case R.id.loginSubmit:
				
				// create a JSON REST object and get the base url from the config file
				JSONConnector con = new JSONConnector();
				con.setBaseUrl(BasewarsConfig.getApiBaseUrl());
				
				// create a sha1 string from the submitted password
				String password = "";
				try {
					password = Sha1.StringToSha1String(this.etPassword.getText().toString());
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				
				// create a list, then will submited with the post
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add( new BasicNameValuePair( "username", this.etUsername.getText().toString() ) );
                nameValuePairs.add( new BasicNameValuePair("password", password) );
                
                JSONObject JSONResponse = con.requestPostObject("login/", nameValuePairs);
				try 
				{
					if(JSONResponse.getBoolean("success"))
					{

				        getSharedPreferences("programSettings",MODE_PRIVATE)
				        .edit()
				        .putString("userId", JSONResponse.getJSONObject("result").getString("id"))
				        .commit();				        
				        // user has logged in so go to the default Activity: BaseMapActivity
				        Intent connect2 = new Intent(this, BaseMapActivity.class);
						startActivity(connect2);
						
						// set result 2, so that previous activity can finish
						setResult(2);
						
						// delete this activity out of the activity stack
						finish();
						
						
					}else
					{
						invalidUsernameOrPassword();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			break;
		}
	}
	
	/** 
	 * error message when app or webserver says its invalid
	 */
	private void invalidUsernameOrPassword() {
		
		Toast.makeText(this, R.string.invalidUsernameOrPassword, Toast.LENGTH_LONG).show();
	}


	@Override
	protected void onStop() 
	{
		// give a result 2 to the register activity so that activity finish.
		setResult(2);
		super.onStop();
	}
	
	@Override
	protected void onDestroy() {
		// give a result 2 to the register activity so that activity finish.
		setResult(2);
		super.onDestroy();
	}
}
